import { install } from 'source-map-support';
install();

import { Command } from 'commander';
import fs from 'fs-extra';
import path from 'path';
import { Convertor } from './Convertor.js';
import { CmdParams, ToolEnv } from './typings';
import dotenv from 'dotenv';
import { toolchain } from './tools/toolchain.js';
import { fileURLToPath } from 'url';
import { ProjIniCfgParser } from './core/ProjIniCfgParser.js';
import { SvnHolder } from './core/SvnHolder.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const myPackage = await fs.readJSON(path.join(__dirname, '../package.json'));

const rmQuotes = (val: string): string => {
    let rst = val.match(/(['"])(.*)\1/);
    if(rst) return rst[2];

    return val;
}

const program = new Command();
program
	.version(myPackage.version, "-v, --version")
	.option("-c, --cmd <xml2json>", "[MUST] command to be executed.")
	.option("-p, --project <string>", "[MUST] Project code.")
	.option("-e, --env <file>", "[MUST] .env file which contains enviroment configurations.", rmQuotes)
	.option("-i, --input [path]", "Input parameter of xls2xml cmd.", rmQuotes)
	.option("-w, --workspace [path]", "Temporary workspace path. Direction only. If workspace is omitted, '.' is assumed.", rmQuotes)
	.option("-d, --debug", "Use debug mode, no svn commit.")
	.option("-f, --force", "Force rebuild and ignore md5 cache.")
	.option("--publish", "Publish mode.")
	.option("--xml2json", "Do xml2json concurrently while executing xls2xml.")
	.option("--remote [string]", "Call by remote command, format: 'code:${code};msgId:${msgId}'.", rmQuotes)
    .parse(process.argv);

const options = program.opts() as CmdParams;

if(fs.existsSync(options.env)) {
    // 读取环境配置
    let envOutput = dotenv.config({ path: options.env });
    if(envOutput.error) {
        console.error('[ERROR]env configuration read error', envOutput.error);
        process.exit(1);
    }
} else if (options.cmd != 'xls2xml') {
    // 转表不需要.env
    console.error('[ERROR].env file not exists:', options.env);
    process.exit(1);
}

if (options.cmd != 'xls2xml') {
    const env = process.env as unknown as ToolEnv;
    if(!env.CFG_LOCAL) {
        console.error('[ERROR]"CFG_LOCAL" value not found in the .evn file.');
        process.exit(1);
    }
    if(!env.CFG_SVN) {
        console.error('[ERROR]"CFG_ENV" value not found in the .evn file.');
        process.exit(1);
    }

    await SvnHolder.Instance.checkSVN(!toolchain.options.debug, env.CFG_LOCAL, env.CFG_SVN);
    
    if(!options.workspace) {
        options.workspace = process.cwd();
    }
}

let replyMsgId = '';
if (options.remote) {
    // 飞书远程执行任务，remote参数格式为：code:${code};msgId:${msgId}，其中code为项目群组代号，msgId为飞书聊天消息ID
    const arr = options.remote.split(';');
    if (arr.length == 2) {
        const [codePairs, msgIdPairs] = arr;
        const code = codePairs.split(':')[1];
        replyMsgId = msgIdPairs.split(':')[1];
        const iCfg = await ProjIniCfgParser.Instance.getProjIniCfgByChatCode(code);
        if (!iCfg) {
            console.error('[ERROR]Project not found via chat code:', code);
            process.exit(1);
        }
        options.project = iCfg.Project.code;
        console.log('real project:', options.project);
    }
}

toolchain.options = options;

const cvt = new Convertor(myPackage.version);
cvt.execute(replyMsgId).catch((reason)=>{
    console.error('[ERROR]Error encoutered!', reason);
    process.exit(1);
});
